import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    children:[
      {
        path: '/',
        component: () => import('../views/Home/StoreList.vue')
      },
      {
        path: '/list',
        component: () => import('../views/order/OrderList.vue')
      },
      {
        path: '/host',
        component: () => import('../views/me/Host.vue')
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login')
  },
  {
    path: '/store',
    name: 'store',
    component: () => import('../views/Home/Store.vue')
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('../views/order/OrderSubmit.vue')
  },
  {
    path: '/address',
    component: () => import('../views/address/AddressList')
  },
  {
    path: '/addressEdit',
    component: () => import('../views/address/AddressEdit')
  },
  {
    path: '/listItem',
    component: () => import('../views/order/OrderDetail')
  },
  {
    path: '/packet',
    component: () => import('../views/service/Packet')
  },
  {
    path: '/service',
    component: () => import('../views/service/Service')
  },
  {
    path: '/focus',
    component: () => import('../views/service/Focus')
  },
  {
    path: '/register',
    component: () => import('../views/Register')
  },
  {
    path: '/update',
    component: () => import('../views/me/UploadAvatar')
  },

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next)=>{
  if(to.path == '/login' || to.path == '/register'){
    next()
  }else{
    if(getCookie("login")=="true"){
      next();
    }else{
      next({path:'/login'});
    }
  }

  // next()
})

//创建一个Cookie
function setCookie(c_name,value,expiredays){
  let exdate = new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "":";expires=" + exdate.toGMT)
}
//获取指定名称的Cookie
function getCookie(name){
  const strcookie = document.cookie;
  const arrcookie = strcookie.split(";");
  for (let i = 0; i<arrcookie.length; i++) {
    const arr = arrcookie[i].trim().split("=");
    if(arr[0] == name){
      return arr[1];
    }
  }
  return "";
}

export default router
